package com.hbsoft.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hb.bean.CallResult;
import com.hb.bean.DDUserInfo;
import com.hb.util.HttpUtil;
import com.hbsoft.common.constant.Constant;
import com.hbsoft.common.enumtype.MethodEnum;
import com.hbsoft.config.SysConfigInfo;
import com.hbsoft.lms.bean.DdDeptBean;
import com.hbsoft.lms.bean.DdUserBean;
import com.hbsoft.lms.vo.DDUserVo;
import com.hbsoft.lms.vo.DepartmentVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.*;

@Component
public class DDUtil {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    public SysConfigInfo SysConfigInfo;

    private String getUserUrl = "https://oapi.dingtalk.com/user/getuserinfo";

    private String getTokenUrl = "https://oapi.dingtalk.com/gettoken";

    private String getTicket = "https://oapi.dingtalk.com/get_jsapi_ticket";

    @Autowired
    private SysConfigInfo sysConfigInfo;


    public CallResult<String> getUser(String code) {
        CallResult<String> result = new CallResult<String>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("access_token", getAccessToken());
        params.put("code", code);
        String u = HttpUtil.sendGet(getUserUrl, params);
        DDUserInfo userInfo = new Gson().fromJson(u, DDUserInfo.class);
        if (userInfo.getErrcode() == 0) {
            result.setCode(0);
            result.setMessage(userInfo.getErrmsg());
            result.setData(userInfo.getUserid());
        } else {
            result.setCode(400);
            result.setMessage(userInfo.getErrmsg());
        }
        return result;
    }


    public String getAccessToken() {
        String url = SysConfigInfo.getDdTokenInterfacePath();
        String params = "Mode=getAccessToken()";
        String token = HttpUtil.sendJSONPost(url, params);
        logger.info("获取钉钉token:{}", token);
        return token;
    }

    public String getAccessToken(String url,String params) {
        //String params = "Mode=getAccessToken()";
        Map<String,Object> param = new HashMap();
        param.put("mode","json");
        param.put("data",params);
        logger.info("post请求：{},{}", url,param.toString());
        String token = HttpUtil.sendPost(url,param);
        logger.info("获取钉钉token:{}", token);
        return token;
    }
    
   /* public String getAccessToken() {
		StringBuffer sb = new StringBuffer();
		sb.append(getTokenUrl + "?");
		sb.append("appkey=" + SysConfigInfo.getDdAppKey());
		sb.append("&appsecret=" + SysConfigInfo.getDdAppSecret());
		String sendGet = HttpUtil.sendGet(sb.toString());
		Map<String, Object> map = GsonUtil.fromJson(sendGet, Map.class);
		String access_token = (String) map.get("access_token");
		return access_token;
	}*/

    /**
     * 网页授权
     *
     * @param
     * @return
     */
//    public String getJSSDKSign(String pageName){
//        pageName = SysConfigInfo.getDd_domainname()+"integral_business/" + pageName;
//        logger.info(pageName);
//        String url = SysConfigInfo.getDdTokenInterfacePath();
//        String params = "Mode=getJSSDKSign('"+SysConfigInfo.getAgentId() +"','"+pageName+ "')";
//        String wxConfig = HttpUtil.sendJSONPost(url, params);
//        logger.info(wxConfig);
//        return wxConfig;
//    }
    /*public String getJSSDKSign(String url) throws Exception {
		String access_token = getAccessToken();
		String ticket = getTicket(access_token);
		String nonceStr = nonce_str(25);
		long timeStamp = System.currentTimeMillis();
		String signature = sign(ticket, nonceStr, timeStamp, url);
		Map<String, Object> configValue = new HashMap<>();
//		configValue.put("jsticket", ticket);
		configValue.put("signature", signature);
		configValue.put("nonceStr", "nonceStr");
		configValue.put("timeStamp", timeStamp);
		configValue.put("corpId", SysConfigInfo.getCorpId());
		configValue.put("agentId", SysConfigInfo.getAgentId());
		System.out.println(GsonUtil.syncToJson(configValue));
		return GsonUtil.syncToJson(configValue);
	}
*/
    public String getTicket(String access_token) {
        StringBuffer sb = new StringBuffer();
        sb.append(getTicket + "?");
        sb.append("access_token=" + access_token);
        String sendGet = HttpUtil.sendGet(sb.toString());
        System.out.println(sendGet + "---------");
        Map<String, Object> map = GsonUtil.fromJson(sendGet, Map.class);
        String ticket = (String) map.get("ticket");
        return ticket;

    }

    public String nonce_str(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }


    /**
     * 从钉钉 获取所有部门
     *
     * @return
     */
    public DepartmentVo getDepts(String getTokenUrl,String tokenParam) {
       /* Map<String, Object> params = new HashMap<String, Object>();
        params.put("access_token", getAccessToken(getTokenUrl,tokenParam));
        String url = "https://oapi.dingtalk.com/department/list";
        Map<String,Object> param = new HashMap<>();
        param.put("url",url);
        param.put("mode","get");
        param.put("data",GsonUtil.toJson(params));
        logger.info("获取钉钉部门：{},{}",sysConfigInfo.getOuterNetInterface(),param);
        String json = HttpUtil.sendPost(sysConfigInfo.getOuterNetInterface(), param);
        logger.info("获取钉钉部门：{}", json);
        DepartmentVo ddDeptAndUser = GsonUtil.fromJson(json, new TypeToken<DepartmentVo>() {
        }.getType());
        return ddDeptAndUser;*/
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("access_token", getAccessToken(getTokenUrl,tokenParam));
        String url = getTokenUrl+"department/list";
        logger.info("获取钉钉部门：{},{}",url,params);
        String json = HttpUtil.sendGet(url, params);
        logger.info("获取钉钉部门：{}", json);
        DepartmentVo ddDeptAndUser = GsonUtil.fromJson(json, new TypeToken<DepartmentVo>() {
        }.getType());
        return ddDeptAndUser;
    }

    /**
     * 从钉钉 获取所有部门
     *
     * @return
     */
    public DepartmentVo getDepts() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("access_token", getAccessToken());
        String json = HttpUtil.sendGet("https://oapi.dingtalk.com/department/list", params);
        logger.info("获取钉钉部门：{}", json);
        DepartmentVo ddDeptAndUser = GsonUtil.fromJson(json, new TypeToken<DepartmentVo>() {
        }.getType());
        return ddDeptAndUser;
    }

    /**
     * 从钉钉 获取部门下所有人员
     *
     * @param deptId
     * @return
     */
    public DDUserVo getUsers(String deptId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("access_token", getAccessToken());
        params.put("department_id", deptId);
        String json = HttpUtil.sendGet("https://oapi.dingtalk.com/user/list", params);
        logger.info("获取钉钉部门人员：{}", json);
        DDUserVo ddUserVo = GsonUtil.fromJson(json, new TypeToken<DDUserVo>() {
        }.getType());
        return ddUserVo;
    }

    /**
     * 从钉钉 获取部门下所有人员
     *
     * @param deptId
     * @return
     */
    public DDUserVo getUsers(String getTokenUrl,String tokenParam,String deptId) {
        CallResult<List<DdUserBean>> result = new CallResult<>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("access_token", getAccessToken(getTokenUrl,tokenParam));
        params.put("department_id", deptId);
        String url = "https://oapi.dingtalk.com/user/list";
        Map<String,Object> param = new HashMap<>();
        param.put("url",url);
        param.put("mode","get");
        param.put("data",GsonUtil.toJson(params));
        logger.info("获取钉钉部门人员：{},{}",url,param);
        String json = HttpUtil.sendPost(url, param);
        logger.info("获取钉钉部门人员：{}", json);
        DDUserVo ddUserVo = GsonUtil.fromJson(json, new TypeToken<DDUserVo>() {
        }.getType());
        return ddUserVo;
    }


    /**
     * 从互邦接口 获取所有部门
     *
     * @return
     */
    public DepartmentVo getDeptsByHbInterface(String url, String methodType) throws Exception {
        Map<String, String> params = new HashMap();
        params.put("app_key", "120001");
        params.put("timestamp", DateUtil.dateFormatString(new Date(), "yyyy-MM-dd hh:mm:ss"));
        params.put("method", "department.list");
        String sign = ApiSign.signTopRequest(params, null, "a17aba5bbacfa2a4c2f6d44f03c9c0fa", "md5");

        Map<String, Object> mapParam = new HashMap();
        mapParam.put("app_key", params.get("app_key"));
        mapParam.put("timestamp", params.get("timestamp"));
        mapParam.put("method", params.get("method"));
        mapParam.put("sign", sign);

        String resultStr = "";
        Map<String,Object> param = new HashMap<>();
        param.put("data",GsonUtil.toJson(mapParam));
        logger.info("获取钉钉部门：url{}",url);
        if (MethodEnum.METHOD_ENUM_POST.getCode().equals(methodType)) {
            param.put("mode","post");
            logger.info("post请求：{}",param);
            resultStr = HttpUtil.sendPost(url,param);
        } else {
            param.put("mode","get");
            logger.info("get请求：{}",param);
            resultStr = HttpUtil.sendGet(url,param);
        }
        logger.info("接口获取钉钉部门,返回信息：{}", resultStr);
        CallResult<DepartmentVo> resultDept = GsonUtil.fromJson(resultStr, new TypeToken<CallResult<DepartmentVo>>() {
        }.getType());
        DepartmentVo departmentVo = resultDept.getData();
        return departmentVo;

/**
 * 从互邦接口 获取部门所有人员
 *
 * @return
 */    }

    public DDUserVo getUserByHbInterface(String url, String methodType, String deptId) throws Exception {
        Map<String, String> params = new HashMap();
        params.put("app_key", "120001");
        params.put("timestamp", DateUtil.dateFormatString(new Date(), "yyyy-MM-dd hh:mm:ss"));
        params.put("method", "user.listbypage");
        params.put("department_id", deptId);
        String sign = ApiSign.signTopRequest(params, null, "a17aba5bbacfa2a4c2f6d44f03c9c0fa", "md5");

        Map<String, Object> mapParam = new HashMap();
        mapParam.put("app_key", params.get("app_key"));
        mapParam.put("timestamp", params.get("timestamp"));
        mapParam.put("method", params.get("method"));
        mapParam.put("department_id", params.get("department_id"));
        mapParam.put("sign", sign);
        String resultStr = "";

        Map<String,Object> param = new HashMap<>();

        param.put("data",GsonUtil.toJson(mapParam));
        logger.info("获取钉钉部门人员：url：{}",url);
        if (MethodEnum.METHOD_ENUM_POST.getCode().equals(methodType)) {
            param.put("mode","post");
            logger.info("post请求：{}",param);
            resultStr = HttpUtil.sendPost(url,param);
        } else {
            param.put("mode","get");
            logger.info("get请求：{}",param);
            resultStr = HttpUtil.sendGet(url, param);
        }
        logger.info("接口获取钉钉人员，参数：{},返回信息：{}", deptId, resultStr);
        CallResult<DDUserVo> resultUser = GsonUtil.fromJson(resultStr, new TypeToken<CallResult<DDUserVo>>() {
        }.getType());
        DDUserVo ddUserVo = resultUser.getData();
        return ddUserVo;
    }

}
